<?php

namespace app\common\controller;

use app\admin\library\Auth;
use think\Config;
use think\Controller;
use think\Hook;
use think\Lang;
use think\Session;
use app\common\model\Config as ConfigModel;

/**
 * 后台控制器基类
 */
class Backend extends Controller
{

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 布局模板
     * @var string
     */
    protected $layout = 'default';

    /**
     * 权限控制类
     * @var Auth
     */
    protected $auth = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id';

    /**
     * 是否是关联查询
     */
    protected $relationSearch = false;

    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = false;
    protected $dataLimitIdent = '';//区分的下级角色
    protected $dataLimitSelf = true;//下级角色是否包含自己
    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'admin_id';

    /**
     * 数据限制开启时自动填充限制字段值
     */
    protected $dataLimitFieldAutoFill = true;

    /**
     * 是否开启Validate验证
     */
    protected $modelValidate = false;

    /**
     * 是否开启模型场景验证
     */
    protected $modelSceneValidate = false;

    /**
     * Multi方法可批量修改的字段
     */
    protected $multiFields = 'status';

    /**
     * 导入文件首行类型
     * 支持comment/name
     * 表示注释或字段名
     */
    protected $importHeadType = 'comment';

    protected $currentAddonName = '';

    /**
     *selectpage 其他条件
     */
    protected $elseWhere = '';
    /**
     * 引入后台控制器的traits
     */
    use \app\admin\library\traits\Backend;

    public function _initialize()
    {
        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;

        // 定义是否Addtabs请求
        !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? TRUE : FALSE);

        // 定义是否Dialog请求
        !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? TRUE : FALSE);

        // 定义是否AJAX请求
        !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());

        $this->auth = Auth::instance();

        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // token
        $token = $this->request->server('HTTP_TOKEN',
            $this->request->request('token', \think\Cookie::get('token')));

        //未登录 停止执行
        $noLoginStop = function ($showType='html') {
            Hook::listen('admin_nologin', $this);
            $url = Session::get('referer');
            $url = $url ? $url : $this->request->url();
            if($showType == 'html') {
                $this->error(__('Please login first'), url('index/login', ['url' => $url]));
            } else {
                output(__('Please login first'), [], -100);
            }
        };

        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin))
        {
            //支持token初始化登录
            if($token) {
                $tokenIslogin = $this->auth->init($token);
                if(!$tokenIslogin) {
                    $noLoginStop('json');
                }
            }
            //检测是否登录
            if (!$this->auth->isLogin())
            {
                $noLoginStop('html');
            }
            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight))
            {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path))
                {
                    Hook::listen('admin_nopermission', $this);
                    $this->error(__('You have no permission'), '');
                }
            }
        }

        // 非选项卡时重定向
        if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs')
        {
            $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function($matches) {
                return $matches[2] == '&' ? $matches[1] : '';
            }, $this->request->url());
            if (Config::get('url_domain_deploy'))
            {
                if (stripos($url, $this->request->server('SCRIPT_NAME')) === 0)
                {
                    $url = substr($url, strlen($this->request->server('SCRIPT_NAME')));
                }
                $url = url($url, '', false);
            }
            $this->redirect('admin/index/index', [], 302, ['referer' => $url]);
            exit;
        }

        // 设置面包屑导航数据
        $breadcrumb = $this->auth->getBreadCrumb($path);
        array_pop($breadcrumb);
        $this->view->breadcrumb = $breadcrumb;

        // 如果有使用模板布局
        if ($this->layout)
        {
            $this->view->engine->layout('layout/' . $this->layout);
        }

        // 语言检测
        $lang = strip_tags(Lang::detect());

        $site = Config::get("site");

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        // 配置信息
        $jsname = file_path(APP_PATH . $this->request->module(), $controllername, '.js', 'assets/js');
        if(!$jsname){
            $jsname = 'backend/' . str_replace('.', '/', $controllername);
        }else{
            $jsname = substr('../../'.APP_DIR.'/'.file_url($jsname), 0, -3);
        }
        $addonCustomTable = [];
        if($this->request->module() == 'admin' && preg_match("/^v\d+\./", $controllername)){
            $temp = explode('.', $controllername);
            $this->currentAddonName = $temp[1];
            $addonjs = APP_PATH . 'admin' .DS . $temp[0] . DS . $temp[1] . DS . 'assets' . DS. 'bootstrap.js';
            if(is_file($addonjs)){
                $jsname = array(
                    $jsname,
                    substr('../../'.APP_DIR.'/'.file_url($addonjs), 0, -3)
                );
            }
            $addonCustomTable = \fast\Addon::getConfigInfo($temp[1], 'customtable');
            if(is_array($addonCustomTable) && $addonCustomTable){
                $addonInfo = get_package_info($temp[1], $temp[0]);
                //$grouplist = $this->auth->getChildrenGroupIds(true);
                foreach($addonCustomTable as $k => &$v){
                    if(!isset($addonInfo['customtable'][$k])){//没有或已取消自定义
                        unset($addonCustomTable[$k]);
                        continue;
                    }
                    foreach($v as $kk => &$vv){
                        //过滤权限
                        $addonActionName = $actionname;
                        if(stripos($actionname, 'index') !== false)$addonActionName = 'index';
                        if(stripos($actionname, 'add') !== false)$addonActionName = 'add';
                        if(stripos($actionname, 'edit') !== false)$addonActionName = 'edit';
                        if(!empty($vv['show'.$addonActionName.'group'])){
                            $vv['show'.$addonActionName.'group'] = array_filter($vv['show'.$addonActionName.'group'], create_function('$a','return trim(strval($a)) !== "";'));
                        }
                        if(!$this->auth->isSuperAdmin() && !empty($vv['show'.$addonActionName.'group'])){
                            if(!in_array($this->auth->identity, $vv['show'.$addonActionName.'group'])){
                                unset($addonCustomTable[$k][$kk]);
                                continue;
                            }
                            /*$checkgroup = array_intersect($grouplist, $vv['show'.$addonActionName.'group']);
                            if(empty($checkgroup)){
                                unset($addonCustomTable[$k][$kk]);
                                continue;
                            }*/
                        }
                        if (in_array($vv['type'], ['select', 'selects', 'checkbox', 'radio', 'array'])){
                            $vv['content'] = ConfigModel::decode($vv['content']);
                        }
                    }
                    unset($vv);
                }
                unset($v);
                $this->assign('addonCustomTable', $addonCustomTable);
            }else{
                $addonCustomTable = [];
            }
        }
        $config = [
            'site'           => array_intersect_key($site, array_flip(['name', 'indexurl', 'cdnurl', 'version', 'timezone', 'languages'])),
            'upload'         => $upload,
            'modulename'     => $modulename,
            'controllername' => $controllername,
            'actionname'     => $actionname,
            'jsname'         => $jsname,
            'moduleurl'      => rtrim(url("/{$modulename}", '', false), '/'),
            'language'       => $lang,
            'fastadmin'      => Config::get('fastadmin'),
            'referer'        => Session::get("referer"),
            'addonCustomTable' => $addonCustomTable,
        ];
        $config = array_merge($config, Config::get("view_replace_str"));

        Config::set('upload', array_merge(Config::get('upload'), $upload));

        // 配置信息后
        Hook::listen("config_init", $config);
        //加载当前控制器语言包
        $this->loadlang($controllername);
        //渲染站点配置
        $this->assign('site', $site);
        //渲染配置信息
        $this->assign('config', $config);
        //渲染权限对象
        $this->assign('auth', $this->auth);
        //渲染管理员对象
        $this->assign('admin', Session::get('admin'));
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        $file = file_path(APP_PATH . $this->request->module(), $name, '.php', 'lang/'.Lang::detect());
        if($file)Lang::load($file);
        /*$temp = explode('.', str_replace(array('/', '\\'), '.', $name));
        $temp1 = array_pop($temp);
        $temp0 = implode('/', $temp);
        $file = APP_PATH . $this->request->module() . '/' . $temp0 . '/lang/' . Lang::detect() . '/' . $temp1 . '.php';
        if(!is_file($file))$file = APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php';
        Lang::load($file);*/
    }

    /**
     * 渲染配置信息
     * @param mixed $name 键名或数组
     * @param mixed $value 值
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
    }

//    //获取组件的身份条件
//    protected function getIdentWhere($addonName='') {
//        $defaultBack = [];
//        $auth = new \app\admin\library\Auth();
//        if($auth->identIsNormalAdmin($auth->identity)) {//普通管理员不受角色限制
//            return $defaultBack;
//        }
//        $configModel = \fast\Addon::getConfigModel($addonName);
//        if(!$configModel) return $defaultBack;
//        $configInfo = \fast\Addon::getConfigInfo($addonName);
//        if(!$configInfo) return $defaultBack;
//        if(!isset($configInfo['map_role'])) return $defaultBack;
//        $map_role = $configInfo['map_role'];
//        if(!$map_role) return $defaultBack;
//        $ident_key = $configInfo['ident_key'];
//        if(!$ident_key) return $defaultBack;
//        if($map_role == 1) {//角色区分为代理 前端config写死1
//            $getType =  'agent';
//        }
//        if($map_role == 2) {//角色区分为商家 继续往下找下级 前端config写死2
//            $getType =  'seller';
//        }
//        $sonIds = $auth->getChildrenAdminIds(true, $getType);
//        return [$ident_key => ['in', $sonIds]];
//    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed $searchfields 快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @param array $changeAgent 是否转义代理为商家 如:['agent_id', 'seller_id']
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null, $extendWhere=[], $changeAgent=false)
    {

        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", "id");
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        $filter = json_decode($filter, TRUE);
        $op = json_decode($op, TRUE);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch)
        {
            if (!empty($this->model))
            {
                $tableName = $this->model->getQuery()->getTable() . ".";
            }
            $sort = stripos($sort, ".") === false ? $tableName . $sort : $sort;
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search)
        {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v)
            {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        foreach ($filter as $k => $v)
        {

            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false)
            {
                $k = $tableName . $k;
            }
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym)
            {
                case '=':
//                    $where[] = [$k, $sym, (string) $v];
//                    break;
                case '!=':
                    $where[] = [$k, $sym, (string) $v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', `{$k}`)";
                    break;
                case 'IN':
                    $where[] = [$k,$sym,explode(',', $v)];
                    break;
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        break;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '')
                    {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    }
                    else if ($arr[1] === '')
                    {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        break;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === ''&&mb_strlen($arr[1])==10)
                    {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1].($sym == '<=' ? ' 23:59:59' : '');
                    }
                    else if ($arr[1] === ''&&mb_strlen($arr[1])==10)
                    {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0].($sym == '<' ? ' 23:59:59' : '');
                    }elseif(mb_strlen($arr[1])==10){
                        $arr[1] .= ' 23:59:59';
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        //如果需要修改代理
        foreach ($where as $k=>$tmpV) {
            if($changeAgent && $tmpV[0] == $changeAgent[0]) {
                unset($where[$k]);
                $agentId = join(',', $tmpV[2]);
                $sellerIds = (new Auth())->getAgentSellerIds($agentId);
                $where[$k][$changeAgent[1]] = ['in', $sellerIds];
            }
        }
        $where = array_merge($extendWhere, $where);

        $where = function($query) use ($where) {
            foreach ($where as $k => $v)
            {
                if (is_array($v) && count($v) > 1)
                {
                    call_user_func_array([$query, 'where'], $v);
                }
                else
                {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit];
    }

    /**
     * 获取数据限制的管理员ID
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitAdminIds()
    {
        if (!$this->dataLimit || !$this->dataLimitIdent || !$this->dataLimitField)
        {
            return null;
        }
        //在管理商家时，管理员也只能看管理员，不能看商家 由管理员列表单独加身份
        if ($this->auth->isSuperAdmin())
        {
            return null;
        }
        $adminIds = [];
        if ($this->dataLimit)
        {
            $adminIds = $this->auth->getChildrenAdminIds($this->dataLimitSelf, $this->dataLimitIdent);
            if(!is_array($adminIds))$adminIds = explode(',', $adminIds);
        }
        return $adminIds;
    }

    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage()
    {
        $args = func_get_args();
        $returned = isset($args[0]) ? $args[0] : false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array) $this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr");
        //排序方式
        $orderby = (array) $this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array) $this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array) $this->request->request("custom/a");
        $order = [];
        foreach ($orderby as $k => $v)
        {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null)
        {
            $where = [$primarykey => ['in', $primaryvalue]];
        }
        else
        {
            $where = function($query) use($word, $andor, $field, $searchfield, $custom) {
                foreach ($word as $k => $v)
                {
                    foreach ($searchfield as $m => $n)
                    {
                        $query->where($n, "like", "%{$v}%", $andor);
                    }
                }
                if ($custom && is_array($custom))
                {
                    foreach ($custom as $k => $v)
                    {
                        $query->where($k, '=', $v);
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            $this->model->where($this->dataLimitField, 'in', $adminIds)->where($this->elseWhere);
        }
        $list = [];
        $total = $this->model->where($where)->where($this->elseWhere)->count();
        if ($total > 0)
        {
            if (is_array($adminIds))
            {
                $this->model->where($this->dataLimitField, 'in', $adminIds)->where($this->elseWhere);
            }
            $list = $this->model->where($where)->where($this->elseWhere)
                ->order($order)
                ->page($page, $pagesize)
                ->field("{$primarykey},{$field}")
                ->field("password,salt", true)
                ->select();
            $list = collection($list)->toArray();
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return $returned ? ['rows' => $list, 'total' => $total] : json(['rows' => $list, 'total' => $total]);
    }

    public function model(){
        return $this->model ? : false;
    }

    public function qrcode($url = '', $label = '', $view = true){
        $url = input('url') ? : $url;
        $label = input('label') ? : $label;
        $view = input('view') ? : $view;
        return create_qrcode($url, $label, $view);
    }
}
